package com.kun.ble;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;

import com.kun.myproject.R;
import com.kun.service.BluetoothLeService;
import com.kun.utils.CommonUtil;
import com.kun.utils.ToastUtil;


/**
 * Created by lirongkun on 16/10/9.
 */
public class BLEUtil {

    private BluetoothLeService mBluetoothLeService;
    private Context context;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    private String DeviceName;

    /**
     *
     * @param context 上下文
     * @param DeviceName 需要连接的蓝牙名称
     */
    public BLEUtil(Context context, String DeviceName){
        this.context = context;
        this.DeviceName = DeviceName;
        init();
    }


    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    public void init(){
        mHandler = new Handler();
        final BluetoothManager bluetoothManager =
                (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if(!BleInit(mBluetoothAdapter)){
            ToastUtil.toastShort(context, R.string.ble_not_supported);
            return;
        }

        if(!mBluetoothAdapter.isEnabled()){
            CommonUtil.showInfoDialog(context, context.getString(R.string.open_bluetooth), null, context.getString(R.string.sure), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mBluetoothAdapter.enable();
                }
            });
        }

        Intent gattServiceIntent = new Intent(context, BluetoothLeService.class);
        context.bindService(gattServiceIntent, mServiceConnection, context.BIND_AUTO_CREATE);//绑定服务
    }


    private boolean BleInit( BluetoothAdapter myBluetoothAdapter){
        Intent gattServiceIntent = new Intent(context, BluetoothLeService.class);

        context.bindService(gattServiceIntent, mServiceConnection,context.BIND_AUTO_CREATE);

        if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            ToastUtil.toastShort(context, R.string.ble_not_supported);
            return false;
        }
        if(myBluetoothAdapter == null){
            ToastUtil.toastShort(context, R.string.error_bluetooth_not_supported);
            return false;
        }
        return true;
    }

    /**
     * 蓝牙扫描
     * @param isConnect 是否已连接
     * @param pd 等待对话框
     */
    public void scanLeDevice(final boolean isConnect,final ProgressDialog pd) {
            // 扫描六秒钟
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(!isConnect) {
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
//                        mBluetoothLeService.broadcastUpdate(mBluetoothLeService.ACTION_GATT_DISCONNECTED);
                        pd.dismiss();
                    }
                }
            }, 6000);
            mBluetoothAdapter.startLeScan(mLeScanCallback);
    }
    // 蓝牙扫描,自动连接
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    String mDeviceAddress = device.getAddress();
                    if (device.getName() == null) return;
                    if (device.getName().equals(DeviceName)&&mDeviceAddress!=null){
//                        若扫描到蓝牙硬件，停止扫描并连接
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
                        if (!mBluetoothLeService.initialize()) {
                            ToastUtil.toastShort(context,"Unable to initialize Bluetooth");
                            return;
                        }
                        ToastUtil.toastShort(context,"正在连接NFC卡片");
                        mBluetoothLeService.connect(mDeviceAddress);
                    }
                }
            };

    /**
     *
     * @param function 功能号
     * @param data 数据
     */
    public void write2ble(int function,byte[] data){
        if (mBluetoothLeService != null)
            mBluetoothLeService.writeStringToGatt(data,function);
    }

    //关闭蓝牙服务
    public void Destroy(){
        mBluetoothLeService.close();
        context.unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }

}
